<template>
  <el-container class="organiza-container">
    <!-- <el-header>{{ L('OrganizationUnits') }}</el-header> -->
    <el-main>
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="tree-container">
            <div class="header-container">
              <div class="title">{{ L('OrganizationUnits') }}</div>
              <div class="action">
                <el-dropdown size="small" @command="handleOuCommand">
                  <el-button size="small" type="primary">
                    更多操作<i class="el-icon-arrow-down" />
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="add-root"><i class="el-icon-circle-plus" />添加根组织</el-dropdown-item>
                    <el-dropdown-item command="add-sub"><i class="el-icon-circle-plus-outline" />添加子组织</el-dropdown-item>
                    <el-dropdown-item command="edit"><i class="el-icon-edit" />修改</el-dropdown-item>
                    <el-dropdown-item command="delete"><i class="el-icon-delete" />删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </div>
            <div class="tree">
              <el-tree
                ref="ouTree"
                v-loading="treeLoading"
                :data="ouData"
                node-key="id"
                :props="defaultProps"
                :highlight-current="true"
                :current-node-key="currentkey"
                :expand-on-click-node="false"
                default-expand-all
                draggable
                :allow-drop="allowDrop"
                @node-click="nodeClick"
                @node-drop="nodeDrop"
              >
                <span
                  slot-scope="{ node, data }"
                  class="custom-tree-node"
                >
                  <svg-icon icon-class="folder" />
                  <span>{{ node.label }}</span>
                  <span class="memberCount">{{ data.memberCount }} 个成员</span>
                </span>
              </el-tree>
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="users-container">
            <div class="header-container">
              <div class="title">{{ !currenNodeData ? '组织成员' : currenNodeData.displayName }}</div>
              <div class="action">
                <el-button
                  v-if="currentkey !== null"
                  size="small"
                  type="primary"
                  icon="el-icon-edit"
                  @click="usersSelection()"
                >添加成员</el-button>
              </div>
            </div>
            <div class="users">
              <el-table
                v-loading="tableLoading"
                size="small"
                :data="userList"
                border
                style="width: 100%"
              >
                <el-table-column
                  :label="L('Actions')"
                  width="70"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      circle
                      @click="deleteUserItem(scope.row)"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  prop="name"
                  label="姓名"
                />
                <el-table-column
                  prop="addedTime"
                  label="添加时间"
                  size="small"
                >
                  <template slot-scope="{row}">
                    <span>{{ row.addedTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                style="margin-top:20px"
                :page-sizes="[10, 50, 100, 150]"
                :page-size="userPageSize"
                :total="userTotalCount"
                layout="total, prev, pager, next"
                @size-change="userPagesizeChange"
                @current-change="userPageChange"
              />
            </div>
          </div>
        </el-col>
      </el-row>

    </el-main>

    <create-or-edit-Ou
      ref="CreateOrEditOu"
      @loadOrganization="loadOrganizationUnits"
    />

    <find-users
      ref="FindUsers"
      :multiple-selection.sync="multipleSelection"
      @reloadUsersAndOU="reloadUsersAndOU"
    />

  </el-container>
</template>

<script>
import CreateOrEditOu from './components/CreateOrEditOu'
import FindUsers from './components/FindUsers'
import { mapActions, mapMutations, mapState } from 'vuex'
import { setTimeout } from 'timers'

export default {
  name: 'OrganizationUnits',
  components: { CreateOrEditOu, FindUsers },
  data() {
    return {
      currentkey: null,
      currenNodeData: null,
      tableLoading: false,
      treeLoading: false,
      ouData: [],
      defaultProps: {
        children: 'children',
        label: 'displayName'
      },
      tableData: [],
      multipleSelection: []
    }
  },
  computed: {
    ...mapState('organizationUnit', ['userList', 'userTotalCount', 'userPageSize', 'userCurrentPage'])
  },
  mounted() {
    this.loadOrganizationUnits()
  },
  methods: {
    ...mapActions('organizationUnit',
      ['getOrganizationUnits',
        'getOrganizationUnitUsers',
        'moveOrganizationUnit',
        'deleteOrganizationUnit',
        'removeUserFromOrganizationUnit']),

    ...mapMutations('organizationUnit', ['SET_USER_PAGE_SIZE', 'SET_USER_CURRENT_PAGE']),

    async loadOrganizationUnits() {
      this.treeLoading = true
      this.ouData = await this.getOrganizationUnits().finally(() => {
        this.treeLoading = false
        setTimeout(() => {
          if (!this.currentkey) {
            this.$store.state['organizationUnit'].userList = []
          }
          this.$refs.ouTree.setCurrentKey(this.currentkey)
        }, 230)
      })
    },

    async loadOrganizationUnitUsers() {
      var pagerequest = {
        id: this.currentkey,
        maxResultCount: this.userPageSize,
        skipCount: (this.userCurrentPage - 1) * this.userPageSize
      }
      await this.getOrganizationUnitUsers(pagerequest)
    },

    reloadUsersAndOU() {
      this.loadOrganizationUnits()
      this.loadOrganizationUnitUsers()
    },

    userPagesizeChange(pagesize) {
      this.SET_USER_PAGE_SIZE(pagesize)
      this.getpage()
    },
    userPageChange(page) {
      this.SET_USER_CURRENT_PAGE(page)
      this.getpage()
    },

    handleOuCommand(command) {
      switch (command) {
        case 'add-root':
          this.$refs.CreateOrEditOu.open({ mode: 'add-root', model: {}})
          break
        case 'add-sub':
          this.$refs.CreateOrEditOu.open({ mode: 'add-sub', model: { parentId: this.currentkey }})
          break
        case 'edit':
          this.$refs.CreateOrEditOu.open({ mode: 'edit', model: { id: this.currenNodeData.id, displayName: this.currenNodeData.displayName }})
          break
        case 'delete':
          this.$confirm(`请确认删除节点 ${this.currenNodeData.label}`, '你确定吗？', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async() => {
            await this.deleteOrganizationUnit({ id: this.currentkey })
            this.loadOrganizationUnits()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
          break
      }
    },
    nodeClick(data) {
      this.currentkey = data.id
      this.currenNodeData = data
      this.loadOrganizationUnitUsers()
    },

    allowDrop(draggingNode, dropNode, type) {
      if (type === 'prev' || type === 'next') { return false } else { return true }
    },
    nodeDrop(fromNode, toNode, pos) {
      const map = { 'before': '之前', 'after': '之后', 'inner': '里面' }

      this.$confirm(`请确认移动 ${fromNode.data.displayName} 到 ${toNode.data.displayName} ${map[pos]}`, '你确定吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await this.moveOrganizationUnit({ id: fromNode.data.id, newParentId: toNode.data.id })
        this.$message({
          type: 'success',
          message: '移动成功!'
        })
      }).catch(() => {
        this.loadOrganizationUnits()
        this.$message({
          type: 'info',
          message: '已取消移动'
        })
      })
    },

    deleteUserItem(row) {
      this.$confirm(`您确定要从组织机构  ${this.currenNodeData.displayName} 中删除成员 ${row.name} ?`, '你确定吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await this.removeUserFromOrganizationUnit({ UserId: row.id, OrganizationUnitId: this.currentkey })
        this.loadOrganizationUnitUsers()
        this.loadOrganizationUnits()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    usersSelection() {
      this.$refs.FindUsers.open({ organizationUnitId: this.currentkey })
    }
  }
}
</script>
<style lang="scss">
.organiza-container {
  .el-header {
    line-height: 60px;
    font-weight: bold;
  }

  .header-container {
    padding: 10px;
    border-bottom: 1px solid #eee;
    .title {
      float: left;
      line-height: 40px;
    }
    .action {
      float: right;
    }
    &:after {
      content: ""; /*设置添加的子元素的内容为空*/
      display: block; /*设置添加的子元素为块级元素*/
      height: 0; /*设置添加的子元素的高度为0*/
      visibility: hidden; /*设置添加的子元素看不见*/
      clear: both; /*给添加的子元素设置clear: both*/
    }
  }

  .tree-container {
    padding: 20px;
    .tree {
      padding: 10px;
    }
    .memberCount {
      opacity: 0.5;
    }
  }

  .users-container {
    padding: 20px;
    .users {
      padding: 10px;
    }
  }
}
</style>

